package com.fresh.fresh.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.fresh.fresh.dao.Files;
import com.fresh.fresh.mapper.FileMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * 文件上传接口
 * */
@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${files.upload.path}")
    private String fileUploadPath;

    @Resource
    FileMapper fileMapper;

    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException {

        String originalFilename = file.getOriginalFilename();
        //获取文件类型
        String type = FileUtil.extName(originalFilename);
        //获取文件大小
        long size =  file.getSize();

        //定义文件唯一标识码
        String uuid = IdUtil.fastSimpleUUID();
        String fileUUID = uuid + StrUtil.DOT + type;



        File uploadPath = new File(fileUploadPath + fileUUID);
        File parentFile = uploadPath.getParentFile();
        //判断目录是否存在，若不存在则创建一个新的文件目录
        if (parentFile != null){
            parentFile.mkdirs();
        }
        String url;

        //存储到磁盘
        file.transferTo(uploadPath);

        //获取上传文件的md5
        String md5 = SecureUtil.md5(uploadPath);

        //从数据库中判断是否纯在相同记录
        Files dbFiles = getLambdaQueryWrapper(md5);

        //获取文件url
        if (dbFiles != null){
            url = dbFiles.getUrl();
            //由于文件已存在，所以删除刚才上传的文件
            uploadPath.delete();
        }else {
            url = "http://localhost:8082/file/" + fileUUID;
        }

        // 存储数据库
        Files save =  new Files();
        save.setName(originalFilename);
        save.setType(type);
        save.setSize(size/1024);
        save.setUrl(url);
        save.setMd5(md5);
        fileMapper.insert(save);
        return url;
    }

    @GetMapping("/{fileUUID}")
    public void download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException{
        File uploadFile = new File(fileUploadPath + fileUUID);

        //设置输出流格式
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Content-Disposition","attachment;filename" + URLEncoder.encode(fileUUID,"UTF-8"));
        response.setContentType("application/octet-stream");

        //读取文件的字节流
        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();

    }

    private Files getLambdaQueryWrapper(String md5){
        LambdaQueryWrapper<Files> lambdaQueryWrapper =  new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Files::getMd5,md5);
        List<Files> filesList = fileMapper.selectList(lambdaQueryWrapper);
        return filesList.size() == 0 ? null : filesList.get(0);
    }
}

